<?php

class AgencyController extends PsController
{

	public function accessRules()
	{
		return CMap::mergeArray(array(
					array('allow',
						'actions' => array('autocomplete', 'ajaxAgencyAddress', 'getSetting', 'updateSetting', 'getAttributeActiveStatus', 'getAttributeSettingLabel', 'getAttributeSettingDefaultValue'),
						'users' => array('@'),
					)), parent::accessRules());
	}

	public function actionAgencyAgentAutocomplete($term = NULL)
	{
		if (strlen($term) > 0) {
			$condition = 'name LIKE :q';
			$params = array(
				':q' => $term . '%',
			);


			$criteria = array(
				'condition' => $condition,
				'order' => 'name ASC',
				'limit' => 25,
				'params' => $params,
			);

			$criteria['condition'] .= ' AND agency_id =:agencyId';
			$criteria['params']['agencyId'] = Yii::app()->user->model->agency_id;

			$users = User::model()->findAll($criteria);

			$userArray = array();
			if (!empty($users)) {
				foreach ($users as $user) {
					$name = $user->name;
					$id = $user->id;
					$userArray[] = array(
						'label' => $name,
						'value' => $name,
						'id' => $id,
					);
				}
			}

			print json_encode($userArray);
		}
	}

	public function actionAjaxAgencyAddress()
	{
		$response = array();
		if (isset($_POST['id'])) {
			$id = $_POST['id'];
			$model = Agency::model()->findByPk($id);
//			if(!empty($model->address_formatted)) {
//				$address = PsAddressFormatter::parseAddress($model->address_formatted);
//			}
//			
			$address = PsAddressFormatter::parseAddress($model->address_formatted);
			$response['data']['block'] = $address['block'];
			$response['data']['street'] = $address['street'];
			$response['data']['floor'] = $address['floor'];
			$response['data']['unit'] = $address['unit'];
			$response['data']['building'] = $address['building'];
			$response['data']['postcode'] = $address['postcode'];
			$response['data']['country_id'] = $model->country_id;
			$response['data']['id'] = $_POST['id'];

			$response['result'] = 'success';
		} else {
			$response['result'] = 'failure';
//			$response['data'] = $_POST;
		}

		print json_encode($response);
	}
	

	public function actionUpdateSetting()
	{
		$response = array();
		$modelName = $_GET['model_name'];
		
		if (isset($_POST['AgencySetting']) && !empty($modelName)) {
			$agency = Yii::app()->user->model->agency;
			$settings = $_POST['AgencySetting']['setting'];
			$key = $modelName . '_' . $agency->id;

			// save to db and create/update cache record
			if ($agency->settings == null) {
				$agency->settings = array();
			} else {
				$modelSettings = $agency->getSetting($key);
				if (is_array($modelSettings)) {
					// is key exist
				} else {
					$modelSettings = array();
				}
			}

			if (!empty($settings) && !empty($settings['attribute'])) {
				$attribute = $settings['attribute'];

				if (empty($modelSettings)) {
					$modelSettings = array();
				}

				foreach ($settings as $k => $v) {
					$modelSettings[$attribute][$k] = $v;
				}

				$agency->setSetting($key, $modelSettings);
			}

			if ($agency->save(true, array('settings'))) {
				// update the changes to cache
				$projectsCache = Yii::app()->cache->get($key);
				if ($projectsCache !== false) {
					// delete the current cache 
					Yii::app()->cache->delete($key);
				}
				// set new value to cache
				Yii::app()->cache->set($key, $modelSettings);

				$response['result'] = 'success';
				$response['data'] = $modelSettings[$attribute];
			} else {
				$response['result'] = 'failure';
				$response['errorMsg'] = 'Error to save setting';
				$response['data'] = $agency->getErrors();
			}
		} else {
			$response['result'] = 'failure';
			$response['errorMsg'] = 'Error to save setting.';
			$response['data'] = $_POST;
		}

		print json_encode($response);
	}

	public function actionGetSetting()
	{
		$response = array();
		$modelName = $_GET['model_name'];
		
		if (isset($_POST)) {
			if (!empty($_POST['attribute']) && !empty($modelName)) {
				$attribute = $_POST['attribute'];
				$agency = Yii::app()->user->model->agency;
				$key = $modelName . '_' . $agency->id;
				$settings = array();

				$modelSettings = $agency->getSetting($key);
				if (is_array($modelSettings)) {

					if (array_key_exists($attribute, $modelSettings)) {
						$settings = $modelSettings[$attribute];
					}
				}

				$response['result'] = 'success';
				$response['settings'] = $settings;
			}
		} else {
			$response['result'] = 'failure';
			$response['errorMsg'] = "Get setting Error";
		}

		print json_encode($response);
	}

}